#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <string>
#include "Common.hpp"
#include "Log.hpp"
using namespace MyLogModule;
class InetAddr
{
private:
    void portNet2Host()
    {
        _port = ::ntohs(_net_addr.sin_port);
    }

    void ipNet2Host()
    {
        // 此种方式inbuffer是局部的，不会造成问题
        char inbuff[64];
        _ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr, inbuff, sizeof(inbuff));
    }

public:
    InetAddr()
    {}
    
    InetAddr(const struct sockaddr_in &addr)
        : _net_addr(addr)
    {
        portNet2Host();
        ipNet2Host();
    }

    // 供服务端创建自己的
    InetAddr(uint16_t port)
        : _port(port), _ip("")
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = ::htons(_port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }

    socklen_t Getlen() { return sizeof(_net_addr); }

    uint16_t getPort() { return _port; }

    std::string getIP() { return _ip; }

    struct sockaddr *Getaddr() { return CONVERSE(&_net_addr); }

    struct sockaddr_in getAddr() { return _net_addr; }

    std::string getInfo() { return _ip + ":" + std::to_string(_port); }

    bool operator==(InetAddr id) { return _ip == id._ip && _port == id._port; }

    void SetAddr(const sockaddr_in& client,socklen_t& len)
    {
        _net_addr = client;
        (void)len;
    }

    ~InetAddr()
    {}

private:
    struct sockaddr_in _net_addr;
    uint16_t _port;
    std::string _ip;
};